package com.zsl.swing.redis.desktop.utils;

import com.alibaba.fastjson.JSONArray;
import com.zsl.swing.redis.desktop.model.CommandModel;
import com.zsl.swing.redis.desktop.window.ZslRedisDesktopMainWindow;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

public class CmdPromptModelUtils {

    private static final String CMD_PATH = "/conf/command.json";

    private static List<CommandModel> commandList;

    private static List<String> commandGroupList;


    public static void loadCommandJson(){
        try(
                InputStream inputStream = CmdPromptModelUtils.class.getResourceAsStream(CMD_PATH);
                BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream,"utf-8"));

        ){
            String line;
            StringBuilder sb = new StringBuilder();

            while((line = reader.readLine()) != null){
                sb.append(line);
            }

            String commandJson = sb.toString();
            commandList = StringUtils.isEmpty(commandJson)?Collections.emptyList():JSONArray.parseArray(commandJson, CommandModel.class);

            commandGroupList = commandList.stream().map(CommandModel::getGroup).distinct().collect(Collectors.toList());

        }catch (Exception e){
            ZslRedisDesktopMainWindow.getZslLogPanel().logError("加载命令JSON时失败，请重新启动：");
            ZslRedisDesktopMainWindow.getZslLogPanel().logError(e);
            commandList = Collections.emptyList();
        }
    }


    public static List<CommandModel> queryLeftLike(String keyword, String group){
        if(StringUtils.isEmpty(group)){
            return StringUtils.isEmpty(keyword)?new ArrayList<>(commandList): commandList.stream().filter(c -> c.getCmd().toUpperCase().startsWith(keyword.toUpperCase())).collect(Collectors.toList());
        }else{
            List<CommandModel> groupList = commandList.stream().filter(c -> c.getGroup().equalsIgnoreCase(group)).collect(Collectors.toList());
            return StringUtils.isEmpty(keyword)?new ArrayList<>(groupList): groupList.stream().filter(c -> c.getCmd().toUpperCase().startsWith(keyword.toUpperCase())).collect(Collectors.toList());
        }
    }


    public static String[] queryCommandGroupList(){
        List<String> targetList = new ArrayList<>();
        targetList.add("");
        targetList.addAll(commandGroupList);

        return targetList.toArray(new String[0]);
    }
}
